--[[--
类名: TaskTrackView.lua
创建日期: 2015-4-22
创建人: 陈小虎
功能描述: 任务追踪视图
修改内容：
修改日期:
修改人:
修改备注:
]]

local ListViewExtend = require("app.widget.ListViewExtend")
local OptionMenu = require("app.widget.optionmenu.OptionMenu")
local TaskTrackRender = import(".renders.TaskTrackRender")
local TaskTrackGrayRender = import(".renders.TaskTrackGrayRender")
local TaskTrackActivityRender = import(".renders.TaskTrackActivityRender")
local UiLoader = cc.uiloader
local ListViewVertical = require("app.widget.listview.ListViewVertical")
local CrossServerGuildWarHelper = require("app.crossServer.views.guildWar.CrossServerGuildWarHelper")

local ActivityNodeTag = 1
local GrayBattleNodeTag = 2
local TaskTrackActivityTag = 3

local TaskTrackView = class("TaskTrackView",function()
    return display.newLayer()
end)

function TaskTrackView:ctor(uiRoot,model)
    cc(self):addComponent("components.behavior.EventProtocol"):exportMethods()

    self:setTouchSwallowEnabled(false)

    self._model = model

    self._uiRoot = uiRoot

    -- 是否在fade动画中
    self._isInFade = false
    self:enableNodeEvents()
    
    self:init()
    
    self:fillTaskList(true)
    self._guildWarListen = EM:on(ViewEvent.CSGuildWar_DesktopTrackView, function()
        self:updateAllTaskItems(true)
    end)
end

function TaskTrackView:onEnter()

end

function TaskTrackView:onExit()
    if self._guildWarListen then
        EM:remove(self._guildWarListen)
    end
end

function TaskTrackView:getModel()
    return self._model
end

-- 获得主任务node
function TaskTrackView:getMainNode()
    return self._mainNode
end

function TaskTrackView:init()
    local rootPanel = self._uiRoot:getChildByName("Panel")
    self._amiPanel = rootPanel:getChildByName("Panel_ami")

    self._mainNode = self._amiPanel:getChildByName("task_zhu")
    self._mainTask = TaskTrackRender.create(self._mainNode)
    self._mainTask:onBtnClick(handler(self, self.onOperate))

    -- setContentSize
    local panel = self._mainNode:getChildByName("Panel")
    self._mainNode:setContentSize(panel:getContentSize())
    self._panelHeight = panel:getContentSize().height
    self._panelHeight = 67

    self._mainPosY = self._mainNode:getPositionY()
    self._activityHeight = 0

    -- 移除 invade
    self._amiPanel:removeChildByName("invade")

    -- self._taskList = self._amiPanel:getChildByName("ListView")
    local scrollViewNode = self._amiPanel:getChildByName("ScrollView")
    self:_initTaskList(scrollViewNode)

    self._arrowNode = rootPanel:getChildByName("arrow")

    self._trackAction = self._uiRoot:getTimeline()
    self._trackAction:gotoFrameAndPause(0)

    self:openTrackAction()

    local touchPanel = rootPanel:getChildByName("bg01")
    touchPanel:setTouchEnabled(true)
    touchPanel:addClickEventListener(function(sender)
        if self._openStatus then
            self:closeTrackAction()
        else
            self:openTrackAction()
        end
    end)

    UD:onChanged("grayBattleInfoUpdate", function() self:updateAllTaskItems(true) end)
end

function TaskTrackView:openTrackAction()

    if self._trackAction then
        if not self._openStatus then
            self._openStatus = true
            self:switchTrackStatus()
            self._trackAction:play("in", false)
            self._trackAction:clearLastFrameCallFunc()
            self._trackAction:setLastFrameCallFunc(function()
                self._trackAction:clearLastFrameCallFunc()
            end)
            self._amiPanel:setVisible(true)
        end
    end
end

function TaskTrackView:closeTrackAction(funcCall)
    if self._trackAction then
        if self._openStatus then
            self._openStatus = false
            self:switchTrackStatus()
            self._trackAction:play("out", false)
            self._trackAction:clearLastFrameCallFunc()
            self._trackAction:setLastFrameCallFunc(function()
                self._amiPanel:setVisible(false)
                self._trackAction:clearLastFrameCallFunc()
            end)
        end
    end
end

function TaskTrackView:switchTrackStatus()
    if self._openStatus then
        self._arrowNode:setRotation(0)
    else
        self._arrowNode:setRotation(-90)
    end
end

----------------------------------新ui开始----------------------------------------------------

function TaskTrackView:startTrackingStatus()
    self:setSelItemStatus()
    self.mTracking = true
end

function TaskTrackView:stopTrackingStatus()
    self.mTracking = false
    self:clearAllItemStatus()
end

function TaskTrackView:fadeInTaskPanel()
    self:trackItemExcuteActions(cc.FadeTo:create(0.5, 255))
end

function TaskTrackView:clearAllItemStatus()
    self._mainTask:setSelectBG(false)

    self._taskList:setCellsShareData(nil)
    self._taskList:notifyCellsShareDataChange()
end

function TaskTrackView:setSelItemStatus()
    local trackTaskId = TaskManager:getCurrentTrackTaskId()
    if self._model:isMainTask(trackTaskId) then
        self._mainTask:setSelectBG(true)
    else
        self._mainTask:setSelectBG(false)
    end
    self._taskList:setCellsShareData({trackTaskId = trackTaskId})
    self._taskList:notifyCellsShareDataChange()
end



function TaskTrackView:_initTaskList(scollviewNode)
    local params = {
		cellConfigs = {
            activity = {renderClass = TaskTrackActivityRender, perNum =1},
            task = {renderClass = TaskTrackRender, perNum =1},
            gray = {renderClass = TaskTrackGrayRender, perNum =1},
        },
        cellTagMarkFunc = function(data)
            return data.tag
        end,
		cellEventProxy = function(eventName, params)
            self:onOperate(eventName, params)
		end,
	}
    self._taskList = ListViewVertical.new( scollviewNode, params )
end


function TaskTrackView:trackItemExcuteActions(action)
    -- TODO 每个item播放action
end

----------------------------------新ui结束----------------------------------------------------

function TaskTrackView:updateMainTask()
    self._mainTask:setData({data = self:getModel():getMainTask()})

    if self.mTracking then
        self:startTrackingStatus()
    end
end

function TaskTrackView:getMainTaskTrackRender()
    return self._mainTask
end



function TaskTrackView:getChampionData()
    local status = Enums.ChampionStatus.NOT_OPEN
    local register = false
    local championStatusData = app:getInst("PvpModel"):getChampionStatusData()
    if championStatusData then
        status = championStatusData.status
        register = championStatusData.register
    end
    if register and (status == Enums.ChampionStatus.PREPARE or status == Enums.ChampionStatus.ENTER or status == Enums.ChampionStatus.BATTLE) then
        return championStatusData
    end
end

function TaskTrackView:getWorldBossData()
    local open = false
    local rewardNotGet = false
    local worldBossStatusData = app:getInst("BossModel"):getWorldBossStatusData()
    if worldBossStatusData then
        open = worldBossStatusData.open
        rewardNotGet = worldBossStatusData.rewardNotGet
    end
    if open or rewardNotGet then
        return worldBossStatusData
    end
end

function TaskTrackView:getChallengeData()
    local open = false
    local challengeStatuData = app:getInst("PvpModel"):getChallengeStatusData()
    if challengeStatuData and challengeStatuData.isOpen then
        return challengeStatuData
    end
end

function TaskTrackView:getEliteMatchData()
    local open = false
    local eliteMatchData = UD.csEliteMatch:getCrossCombatStatus()
    if eliteMatchData and eliteMatchData.isOpen then
        return eliteMatchData
    end
end

function TaskTrackView:getCrossMatchDatas()
    local datas = app:sendMsg("TeamModel", "getCrossMatchDatas")
    return datas
end

function TaskTrackView:updateAllTaskItems(bLayout)
    local tasksData = {}
  
    -- 灰烬入侵
    if UD:hasGrayBattleInfo() then 
        table.insert(tasksData, {tag = "gray"})
    end

    --冠军赛、
    local championData = self:getChampionData()
    if championData then
        table.insert(tasksData, {tag = "activity", type = 1, data = championData})
    end
    --世界boss、
    local worldBossData = self:getWorldBossData()
    if worldBossData then
        table.insert(tasksData, {tag = "activity", type = 2, data = worldBossData})
    end
    --挑战赛
    local challengeData = self:getChallengeData()
    if challengeData then
        table.insert(tasksData, {tag = "activity", type = 3, data = challengeData})
    end

    --跨服战
    if CrossServerGuildWarHelper.isGuildWarFuncOpen() and UD.csGuildWarData:isOpen() then
        table.insert(tasksData, {tag = "activity", type = 4})
    end
    --跨服精英赛
    local eliteMatchData = self:getEliteMatchData()
    if eliteMatchData then
        table.insert(tasksData, {tag = "activity", type = 5, data = eliteMatchData})
    end

    --跨服匹配
    local crossMatchDatas = self:getCrossMatchDatas()
    for i,data in ipairs(crossMatchDatas) do
        table.insert(tasksData, {tag = "activity", type = 6, data = data})
    end

    -- 其他
    local tasks = self:getModel():getTasks()
    for k, task in ipairs(tasks) do
        table.insert(tasksData, {tag = "task", data = task})
    end
    if bLayout then
        self._taskList:reloadData(tasksData, {startIndex = 1})
    else
        self._taskList:reloadData(tasksData)
    end
    
end

function TaskTrackView:fillTaskList(bLayout)
    self:updateAllTaskItems(bLayout)
    self:updateMainTask()
end

function TaskTrackView:onOperate(op, data)
    if op == "onTrackItem" then
        self:dispatchEvent({name = "onTrackItem", taskConfig = data})
    elseif op == "openGrayBattle" then
        app:sendMsg("GrayBattleController", "openView")
    end
end


return TaskTrackView
